var http = require('http');
var express = require('express');
var restful = require('node-restful');
var bodyParser = require('body-parser');
var mongoose = restful.mongoose;

var app = express();
app.use(bodyParser.json());

// ======================================================
mongoose.connect('mongodb://localhost/restful');

var ProductSchema = mongoose.Schema({
	name: String,
	sku: String,
	price: Number
});

var Products = restful.model('products', ProductSchema);

Products.methods(['get','put','post','delete']);
Products.register(app, '/api/products');
// ======================================================

var people = [{dni:111, name:'Pepe', age:30},
			  {dni:222, name:'Jose', age:20},
			  {dni:333, name:'Carlos', age:36}];

app.get('/people', function(req, res){
	res.send(people);
});

app.get('/people/:dni', function(req, res){
	var person = people.filter(function(p){
		return p.dni == req.params.dni;
	})[0];

	if (!person){
		return res.sendStatus(404);
	}
	res.send(person);
});

app.post('/people/:dni', function(req, res){
	people.push(req.body);
	res.sendStatus(201);
});

app.listen(3000);
console.log('Server is running at port 3000');
